from multiprocessing import Process, JoinableQueue
import time
import random

# python的Queue的get和put都为阻塞的, 若想非阻塞则用get(False),put(obj, False)
 
def consumer(q, man):
    while True:
        food = q.get()
        time.sleep(random.randint(1, 3))
        print('%s 吃 %s' % (man, food))
        q.task_done()  # 发送信号给q.join(),说明已经从队列中取走一个数据并处理完毕
 
 
def producer(q, man, food):
    for i in range(3):
        time.sleep(random.randint(1, 3))
        food_id = '%s%s' % (food, i)
        q.put(food_id)
        print('%s 生产了 %s' % (man, food_id))
    q.join()    # 等到消费者把自己放入队列中的所有的数据都取走之后，生产者才结束
 
 
if __name__ == '__main__':
    '''
    1. 主进程等生产者p1,p2,p3结束
    2. 而p1，p2，p3，是在消费者把所有数据都取干净之后才会结束
    3. 所以一旦p1,p2,p3结束了，证明消费者也没必要存在了，应该随着主进程一块死掉，因而需要将消费者设置成守护进程
    '''
    q = JoinableQueue()
    p1 = Process(target=producer, args=(q, 'Jim', '包子'))
    p2 = Process(target=producer, args=(q, 'Jenny', '烧麦'))
    p3 = Process(target=producer, args=(q, 'James', '豆浆'))
    c1 = Process(target=consumer, args=(q, 'Tom'))
    c2 = Process(target=consumer, args=(q, 'Tony'))
    c1.daemon = True
    c2.daemon = True
    p1.start()
    p2.start()
    p3.start()
    c1.start()
    c2.start()
    p1.join()
    p2.join()
    p3.join()
